package top.tagao.m01_structuralPatterns.s_12_flyweight;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author fu-xiao-liu
 * @Date 2022/8/7 17:46
 */
public class Factory {
    private static Map<String,AbstractWaitressFlyweight> pool = new HashMap<>();
    //享元，池子中有对象
    static {
        BeautifulWaitress waitress =
                new BeautifulWaitress("11","张三",18);


        BeautifulWaitress waitress2 =
                new BeautifulWaitress("22","李四",20);


        pool.put(waitress.id,waitress);
        pool.put(waitress2.id,waitress2);
    }
    public void addWaitress(AbstractWaitressFlyweight waitressFlyweight){
        pool.put(UUID.randomUUID().toString(),waitressFlyweight);
    }
    public static AbstractWaitressFlyweight getFlyweight(String workerName,String userName){
        AbstractWaitressFlyweight flyweight = pool.get(workerName);
        //如果对象为空，申请其他客服进行服务
        if (flyweight == null) {
            for (AbstractWaitressFlyweight ab : pool.values()) {
                if (ab.isCanService()) {
                    ab.setUser(userName);
                    return ab;
                }
            }
            return null;
        }
        flyweight.setUser(userName);
        return flyweight;
    }
}
